package com.yix.demo;

import com.yix.util.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import static com.yix.util.DBUtil.getPGConnection;

public class DatabaseDemo {
    public static void main(String[] args) {
        String databaseName = "jdbc_demo_db";
        createDatabase(databaseName);


    }

    /**
     * 创建数据库
     *
     * @param databaseName 数据库名称
     */
    private static void createDatabase(String databaseName) {
        Boolean databaseExists = DBUtil.checkDatabaseExists(databaseName);

        if (databaseExists) {
        } else {
            String createDatabase = "CREATE DATABASE " + databaseName;

            try (Connection connection = getPGConnection();
                 Statement stmt = connection.createStatement()) {
                stmt.execute(createDatabase);
                System.out.println("数据库创建成功");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("数据库连接错误");
            }
        }
    }

    /**
     * 删除数据库
     *
     * @param databaseName 数据库名称
     */
    private static void deleteDatabase(String databaseName) {
        String dropDatabaseSql = "DROP DATABASE IF EXISTS " + databaseName;
        try (Connection conn = getPGConnection();
             Statement stmt = conn.createStatement()) {
            stmt.execute(dropDatabaseSql);
            System.out.println("数据库 '" + databaseName + "' 删除成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}